<?php 
namespace App\Http\Components;

use App\Http\Components\AppComponent;
use App\Http\Components\AccountComponent;
use App\Models\MatchDetailModel;
use App\Models\MatchRequestModel;
use App\Models\MatchResponseModel;
use Illuminate\Http\Request;
use App\library\UtilFunction;
use DB;
use App\Models\CorpsModel;
use App\Models\UserProfileModel;
use App\Models\CorpsTeamModel;
use App\Models\CorpsAccountModel;
use App\Models\AccountCorpsTemppayModel;
/**
* 
*/
class CorpsComponent extends AppComponent{
	
	public function __construct(){
        parent::__construct();
	}

    public static function corps_role($user_id,$corps_id){
        // 当前查看战队的信息
        if ($corps_info = CorpsModel::where('corps_id',$corps_id)->select(['badge' ,'captain_name' ,'user_id' ,'leader_id' ,'name' ,'sport' ,'credit' ,'level' ,'exp' ,'avg_age' ,'avg_height' ,'avg_weight' ,'challenge' ,'team_count' ,'win_rate' ,'slogan' ,'name_first' ,'secretary_id'])->first()){
            $corps_info = $corps_info->toArray();
        } else {
            return SELF::_json('0','未查询到战队信息');
        }

        // 用户有的战队
        $user_corps = CorpsTeamModel::where('user_id',$user_id)->where('status','formal')->lists('corps_id')->toArray();
        
        if ($corps_info['user_id'] == $user_id) {
            $corps_role = 'admin';
            $role_allow = array('leader_id','team_count','challenge','slogan','corps_account','win_rate','secretary');
        }elseif ($corps_info['leader_id'] == $user_id) {
            $corps_role = 'leader';
            $role_allow = array('team_count','challenge','slogan','corps_account','win_rate','secretary');
        }elseif(in_array($corps_id, $user_corps)){
            $corps_role = 'member';
            $role_allow = array('team_count','corps_account','challenge','win_rate');
        }elseif($corps_info['secretary_id'] == $user_id){
            $corps_role = 'secretary';
            $role_allow = array('team_count','corps_account','challenge','win_rate');
        }else{
            $corps_role = 'viewer';
            $role_allow = array('win_rate');
        }

        app()->configure('ppurl');
        $img_url = config('ppurl.img_url');
        app()->configure('corps_lv_member');
        $member_limit = config('corps_lv_member.content');
        
        $corps_exp = SELF::corps_exp($corps_info['level'],$corps_info['exp'],$corps_info['team_count']);

        $corps_info['badge']       = $img_url.$corps_info['badge'];     
        $corps_info['win_rate']    = $corps_info['win_rate'] * 100;     
        $corps_info['member_limit']= $member_limit[$corps_info['level']];
        $corps_info['level']       = $corps_exp['lv'];
        $corps_info['exp']         = $corps_exp['exp'];
        $corps_info['lv_exp']      = $corps_exp['lv_exp'];
                
        $return_data = array();
        $return_data['corps_role']  = $corps_role;
        $return_data['role_allow']  = $role_allow;
        $return_data['base_info']   = $corps_info;
        
        return $return_data;
    }

    // 战队成员限制
    public static function member_limit($corps_id,$corps_level = false){
        if (!$corps_level) {
            $corps_data = CorpsModel::where(['corps_id'=>$corps_id])->first();
            $corps_exp = SELF::corps_exp($corps_data->level,$corps_data->exp,$corps_data->team_count);
            $corps_level = $corps_exp['lv'];
        }
        app()->configure('corps_lv_member');
        $corps_lv_member = config('corps_lv_member.content');
        $limit_member_count = $corps_lv_member[$corps_level];
        $corps_team_count = $corps_data->team_count;
        return ($limit_member_count - $corps_team_count);
    }

    // 获取战队经验等级
    public static function corps_exp($corps_level,$corps_exp,$team_count){
        $return_data = array();

        app()->configure('corps_lv_exp');
        $lv_corps_exp = config('corps_lv_exp.content');
        
        $corps_exp_limit = 0;
        /*需要判断减去后的等级是否大于下一等级*/
        foreach ($lv_corps_exp as $config_lv => $config_exp) {
            // 如果当前经验大于经验限制
            if (($corps_exp - $corps_exp_limit) >= $config_exp) {
                $corps_exp_limit = $corps_exp_limit + $config_exp;
            }else{
                break;
            }
        }
        // if ($team_count >= 10) {
            $return_data['exp'] = ($corps_exp >= $corps_exp_limit)?($corps_exp - $corps_exp_limit):0;
            $return_data['lv'] = $config_lv;
            $return_data['lv_exp'] = "".$lv_corps_exp[$config_lv];
        // }else{
        //     $return_data['exp'] = $corps_exp;
        //     $return_data['lv'] = '1';
        //     $return_data['lv_exp'] = "".$lv_corps_exp['1'];
        // }
        return $return_data;
    }

    public static function update_corps($corps_id){
        $team_list = DB::table('corps_team')
        ->leftJoin('user_profile','corps_team.user_id','=','user_profile.user_id')
        ->where(['corps_team.corps_id'=>$corps_id,'corps_team.status'=>'formal'])
        ->select(['user_profile.age','user_profile.height','user_profile.weight'])->get();
        
        $team_age = array();
        $team_height = array();
        $team_weight = array();
        foreach ($team_list as $team_row) {
            $team_age[] = $team_row->age;
            $team_height[] = $team_row->height;
            $team_weight[] = $team_row->weight;
        }

        $team_count = count($team_list);
        $avg_age = array_sum($team_age) / $team_count;
        $avg_height = array_sum($team_height) / $team_count;
        $avg_weight = array_sum($team_weight) / $team_count;

        if($corps = DB::table('corps')->where('corps_id',$corps_id)->select(['name','badge'])->first()){
            DB::table('corps')->where('corps_id',$corps_id)->update(['team_count'=>$team_count,'avg_age'=>$avg_age,'avg_height'=>$avg_height,'avg_weight'=>$avg_weight]);
        }

        /*更新战队钱包*/
        $bill_amount = DB::table('account_corps_bill')->where(['corps_id'=>$corps_id,'status'=>'succeeded'])->sum('amount');
        DB::table('corps_account')->where('corps_id',$corps_id)->update(['balance'=>$bill_amount]);
    }

    /*战队支付到临时钱包*/
    public static function temp_pay($user_id,$corps_id,$amount,$subject,$body=''){
        try {
            $return_data = SELF::corps_role($user_id,$corps_id);
            if ($return_data['corps_role'] == 'admin' || $return_data['corps_role'] == 'leader') {
            }else{
                return SELF::_json('0','只有战队队长或领队才能发起约战:'.$return_data['corps_role']);
            }
            $amount = floatval($amount);

            // if ($amount <= 0) {
            //     return SELF::_json('0','金额不正确');
            // }

            $corps_account = CorpsAccountModel::where('corps_id',$corps_id)->first();
            if($corps_account){
                $corps_balance = $corps_account->balance;
            }else{
                return SELF::_json('0','战队信息不正确');   
            }

            if (!$body || strstr($body, '{corps.name}')) {
                $body = $body?$body:'{corps.name} 支付操作';
                $corps = CorpsModel::where('corps_id',$corps_id)->first();
                if($corps){
                    $body = str_replace('{corps.name}', $corps->name, $body);
                }else{
                    return SELF::_json('0','战队信息不正确');   
                }
            }

            // 战队提现支付
            if ($corps_balance >= $amount) {
                $accountCommon = new AccountCorpsTemppayModel();
                $accountCommon->user_id = $user_id;
                $accountCommon->corps_id = $corps_id;
                $accountCommon->order_no = AccountComponent::generate_order_no('corps_temppay','dddpocket');
                $accountCommon->amount = $amount;
                $accountCommon->channel = 'dddpocket';
                $accountCommon->subject = $subject;
                $accountCommon->body = $body;
                $accountCommon->status = 'succeeded';
                $Common_status = $accountCommon->saveOrFail();
                if ($Common_status) {
                    $order_data = $accountCommon->toArray();
                    /*操作余额*/
                    // return SELF::_json('1','支付成功');
                    return $order_data;
                }else{
                    return SELF::_json('0','战队临时钱包支付失败',array('corps_balance'=>$corps_balance));
                }
            }else{
                return SELF::_json('0','战队钱包余额不足',array('corps_balance'=>$corps_balance));   
            }
        } catch (\Exception $e) {
            return SELF::_json('0','支付失败');
        }
    }

    public static function temp_refund($user_id,$corps_id,$order_no,$need_notice = true,$amount = ''){
        // AccountCorpsTemppayModel::where(['corps_id'=>$corps_id,'order_no'=>$order_no])->update(['status'=>'refund']);
        $temp_pay = AccountCorpsTemppayModel::where(['corps_id'=>$corps_id,'order_no'=>$order_no,'status'=>'succeeded'])->first();
        if ($temp_pay) {
            $temp_pay->status = 'refund';
            $temp_pay->saveOrFail();
        }else{
            return false;
        }
        if ($need_notice) {
            $corps = CorpsModel::where('corps_id',$corps_id)->first();
            RongCloudComponent::system_publish($corps->user_id,'战队余额变动提醒','对方未接受您的挑战，付款已退回','','me');
            if($corps->leader_id){
                RongCloudComponent::system_publish($corps->leader_id,'战队余额变动提醒','对方未接受您的挑战，付款已退回','','me');
            }
        }
        return true;
    }


    /**
     * 战队积分经验计算
     * @param $type
     * @param $corps_id
     */
    public static function mission_exp($type,$corps_id){

        $corps = CorpsModel::where('corps_id',$corps_id)->first();

        app()->configure('mission_rule');
        $mission_rule = config('mission_rule.corps');

        $member_count = CorpsTeamModel::where('corps_id',$corps_id)->where('status','formal')->count();
        switch ($type) {
            //创建战队
            case 'corps_create':
                $corps->exp = $corps->exp + $mission_rule[$type]['exp'];
                $corps->credit = $corps->credit + $mission_rule[$type]['credit'];
                break;
            //战队达到10人
            case 'corps_team_count':
                if( $member_count == 10 ){
                    $corps->exp = $corps->exp + $mission_rule[$type]['exp'];
                    $corps->credit = $corps->credit + $mission_rule[$type]['credit'];
                }
                break;
            //约战/应战一次
            case 'corps_match':
                $exist_request = MatchRequestModel::where('corps_id',$corps_id)->count();
                $exist_response = MatchResponseModel::where('corps_id',$corps_id)->count();
                if(($exist_response+$exist_request)==1){
                    $corps->exp = $corps->exp + $mission_rule[$type]['exp'];
                    $corps->credit = $corps->credit + $mission_rule[$type]['credit'];
                }
                break;
            //周踢球达两次
            case 'corps_match_count':
                //当前周的开始和结束时间
                $sdefaultDate = date("Y-m-d");
                //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                $first=1;
                //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                $w=date('w',strtotime($sdefaultDate));
                //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
                $week_start=date('Y-m-d 00:00:00',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
                //本周结束日期
                $week_end=date('Y-m-d 23:59:59',strtotime("$week_start +6 days"));
                $match_count = MatchDetailModel::where(function($query) use ($corps_id){
                    $query->orWhere('request_corps_id',$corps_id)->orWhere('response_corps_id',$corps_id);
                })->where('status','finish')->whereBetween('end_time',[$week_start,$week_end])->count();
                if($match_count == 2){
                    $corps->exp = $corps->exp + $mission_rule[$type]['exp'];
                    $corps->credit = $corps->credit + $mission_rule[$type]['credit'];
                }
                break;
            //友谊赛-无裁判  竞技赛败方
            case 'no_judge':
            case 'match_judge_lose':
                $corps->exp = $corps->exp + 5;
                $corps->credit = $corps->credit + 100;
                break;
            //竞技赛胜方
            case 'match_judge_win':
                $corps->exp = $corps->exp + 20;
                $corps->credit = $corps->credit + 200;
                break;
            //竞技赛平局
            case 'match_judge_tie':
                $corps->exp = $corps->exp + 10;
                $corps->credit = $corps->credit + 150;
                break;
        }
        $corps->saveOrFail();
    }
}
